package cfca.paperless.client.servlet._8_local;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import cfca.paperless.client.bean.MultiDataBean;
import cfca.paperless.client.bean.ProofUserInfo;
import cfca.paperless.client.bean.SignLocation;
import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.client.servlet.PaperlessClientLocal;
import cfca.paperless.client.servlet.PaperlessLocalConfig;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PaperlessUtil;
import cfca.paperless.client.util.PdfUtil;
import cfca.sadk.algorithm.common.Mechanism;

public class SealAutoProofPdfLocalTest01 {

    /**
     * PDF本地计算hash并合成签名，使用临时申请的场景证书，可以用于处理大文件和文件需要保密的场景
     * 
     * @param args
     * @throws IOException
     * @throws
     */
    public static void main(String[] args) throws Exception {
        try {
            long timeStart = System.currentTimeMillis();// 开始时间
            // 待签章pdf
            String filePath = "./TestData/file.pdf";
            byte[] pdf = FileUtils.readFileToByteArray(new File(filePath));
            // 印模图片
            byte[] handwritingImage = FileUtils.readFileToByteArray(new File("./TestData/seal.png"));
            // 如下为本地合成的多媒体信息
            // byte[] handwritingData = handwritingImage;
            byte[] identificationFrontData = FileUtils.readFileToByteArray(new File("./TestData/1.png"));
            byte[] identificationBackData = FileUtils.readFileToByteArray(new File("./TestData/2.png"));
            List<MultiDataBean> list = new ArrayList<MultiDataBean>();
            list.add(new MultiDataBean(handwritingImage, "handwritingImage.png", "2"));// 手写签名图片
            list.add(new MultiDataBean(identificationFrontData, "identificationFrontImage.png", "2"));// 身份证正面
            list.add(new MultiDataBean(identificationBackData, "identificationBackImage.png", "2"));// 身份证反面

            String proofHashAndMultiData1[] = PaperlessUtil.getProofHashAndMultiData(list);
            String proofHashXml = proofHashAndMultiData1[0];
            // 计算pdf内容hash
            String pdfContentHash = PdfUtil.calculatePdfContentHash(pdf, new Mechanism(Mechanism.SHA1));
            proofHashXml = addProofToXml(proofHashXml, "pdfHash.pdf", pdfContentHash);
            // 合成proofHash
            pdf = PdfUtil.compoundPdfDataByAttachment(pdf, proofHashXml.getBytes(), "proofHash.xml");
            // 合成多媒体文件
            for (MultiDataBean multiDataBean : list) {
                pdf = PdfUtil.compoundPdfDataByAttachment(pdf, multiDataBean.getMultiData(), multiDataBean.getFileName());
            }

            String selfExtValue = proofHashXml;
            // 初始化客户端对象
            PaperlessClient clientExtBean = new PaperlessClient(PaperlessLocalConfig.extUrl, 10000, 60000);// 无纸化辅助接口的访问URL

            // 以下代码为获取印章编码对应公钥证书
            PaperlessClient clientAssistBean = new PaperlessClient(PaperlessLocalConfig.assistUrl, 10000, 60000);// 无纸化辅助接口的访问URL

            PaperlessClientLocal paperlessClientLocal = new PaperlessClientLocal(clientExtBean, clientAssistBean, PaperlessLocalConfig.operatorCode);
            paperlessClientLocal.initTimestampServer("http://127.0.0.1:8080/Proxy/Timestamp", "", "");
            
            String userName = "张珊珊";
            String identificationType = "0";
            String identificationNo = "454212556565656";
            String keyAlg = "RSA";
            int keyLength = 2048;
            ProofUserInfo proofUserInfo = new ProofUserInfo(userName, identificationType, identificationNo, keyAlg, keyLength, selfExtValue);
            SignLocation signLocation = new SignLocation("代理人签名", "R", 0, 0);// 签名位置
            
            byte[] sealedPdfData = paperlessClientLocal.sealAutoProofPdfLocal(pdf, proofUserInfo, handwritingImage, 0.75f, signLocation);
            
//            userName = "张三丰";
//            identificationType = "0";
//            identificationNo = "454212556562222";
//            keyAlg = "RSA";
//            keyLength = 2048;
//            proofUserInfo = new ProofUserInfo(userName, identificationType, identificationNo, keyAlg, keyLength, selfExtValue);
//            signLocation = new SignLocation("代理人签名", "R", 100, 0);// 签名位置
//            sealedPdfData = paperlessClientLocal.sealAutoProofPdfLocal(sealedPdfData, proofUserInfo, handwritingImage, 0.75f, signLocation);
            
            String outputFilePath = "./TestData/output/signAutoPdfProofHash4-" + new File(filePath).getName() + ".pdf";
            System.out.println("pdfSealVerifier ok " + outputFilePath);
            IoUtil.write(outputFilePath, sealedPdfData);

            long timeEnd = System.currentTimeMillis();// 结束时间
            System.out.println("time:" + (timeEnd - timeStart));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private static String addProofToXml(String xmlContent, String fileName, String hash) throws DocumentException {
        Document document = DocumentHelper.parseText(xmlContent);
        Element root = document.getRootElement();
        Element newElement = root.addElement("Proof");
        newElement.addAttribute("fileName", fileName);
        newElement.addAttribute("hash", hash);
        return document.asXML();
    }

}
